<?php
namespace My\Controller;

use Utuo\BackgroundController;
use Utuo\PHPExcel;

class DriverController extends BackgroundController
{

    private $termId = null;

    private $termConfig = null;

    private $rank = null;

    private $status = array(
        '0' => '已禁用',
        '1' => '正常'
    );

    public function _initialize()
    {
        $this->termId = I('request.term_id', 0, "intval") or $this->error('请先选择期次');
        $this->termConfig = $this->getTermConfig();
        $this->setControllerTitle("司机管理");
        $this->setActionTitle(array(
            'index' => '司机管理',
            'voteList' => '投票明细列表',
            'voteChart' => '投票分布图',
            'dayVotes' => '日投票数',
            'dayVoteChart' => '每日得票分布图',
        	'getIpRepeat' => 'IP投票数',
            'recycle' => '回收站'
        ), '', 'term_id=' . $this->termId);
        $this->setActionNav("index,recycle");
        foreach ($this->status as $k => $v) {
            $this->setLinkNav($v, U("Driver/index", "status={$k}&term_id={$this->termId}"));
        }
        $this->rank = new \Utuo\Rank(array(
            'namespace' => $this->termConfig['rank_name']
        ));
        $this->assign("termId", $this->termId);
    }

    public function inputAction()
    {
        // $model = M('Driver');
        // $old = $model->where("term_id=1 AND status=1 AND is_deleted=0 AND cid=43 AND id!=35")->field("cid,open_id,service_no,plate_number,name,tel,create_time")->select();
        // foreach ($old as &$v){
        // $v['term_id'] = 3;
        // }
        // $model->addAll($old);
    }

    public function getLists($is_deleted = 0)
    {
        $status = I("status", - 1, 'intval');
        $page = I('p', 0, 'intval');
        $condition = array(
            'a.is_deleted' => $is_deleted,
            'a.cid' => $this->aid,
            'a.term_id' => $this->termId
        );
        $status !== - 1 and $condition['status'] = $status;
        $m = M("Driver a")->where($condition)->field("a.*");
        $n = clone $m;
        $driverCount = $n->count();
        $driverLists = $m->page($page)
            ->limit($this->getPageSize())
            ->order("a.vote desc,a.id asc")
            ->select();
        foreach ($driverLists as &$v) {
            $v['statusOptions'] = $this->getOption($this->status, $v['status']);
            $v['rank'] = $this->rank->getRank($v['id']) === false ? '-' : $this->rank->getRank($v['id']) + 1;
            $v['cleanVote'] = M('DriverVote')->where(array('term_id'=>$v['term_id'],'driver_id'=>$v['id']))->getField('count(distinct ip) as vCount');
        }
        $this->showPage($driverCount, $this->getPageSize());
        $this->assign("driverLists", $driverLists);
        $this->assign('driverCount', $driverCount);
        $this->assign('voteCount', M('DriverVote')->where("cid=%d AND term_id=%d", $this->aid, $this->termId)
            ->count());
        $this->display();
    }

    /**
     * 日投票量
     */
    public function dayVotesAction()
    {
        $driverId = I('id', 0, 'intval');
        $dayVotes = M("DriverVote")->where(array(
            'driver_id' => $driverId,
            'term_id' => $this->termId
        ))
            ->group("from_unixtime(create_time, '%Y-%m-%d')")
            ->order("create_time desc")
            ->field("from_unixtime(create_time, '%Y-%m-%d') as date, count(id) as count")
            ->select();
        $driver = M("Driver")->where("id=%d", $driverId)->find();
        $this->assign("driver", $driver);
        $this->assign("dayVotes", $dayVotes);
        $this->display();
    }
    
    // 查看每个司机的得票分布图
    public function voteChartAction()
    {
        $driver_id = I('id', 0, 'intval');
        $days = 5;
        
        $votes = array();
        
        $now = min(time(), $this->termConfig['end_time']);
        
        for ($i = 0; $i < $days; $i ++) {
            $date = date('Y-m-d', strtotime("-$i day", $now));
            $votes[] = $this->getDayVote($driver_id, $date);
        }
        
        $driver = M('Driver')->find($driver_id);
        $this->assign('driver', $driver);
        $this->assign('votes', $votes);
        $this->display();
    }
    
    // 日投票分布图
    public function dayVoteChartAction()
    {
        $driver_id = I('id', 0, 'intval');
        $now = min(time(), $this->termConfig['end_time']);
        $date = date('Y-m-d', $now);
        $days = intval(date('d',$now));
        $vote = $this->getDayVote($driver_id, $date);
        
        $dayVotesList = M("DriverVote")->where(array(
            'driver_id' => $driver_id,
            'term_id' => $this->termId
        ))
        ->group("from_unixtime(create_time, '%Y-%m-%d')")
        ->order("create_time desc")
        ->field("from_unixtime(create_time, '%e') as date, count(id) as count")
        ->select();
        
        $dayVotes = array();
        foreach ($dayVotesList as $v){
            $dayVotes[$v['date']] = $v['count'];
        }
        
        $driver = M('Driver')->find($driver_id);
        $this->assign('driver', $driver);
        $this->assign('days',$days);
        $this->assign('year',date('Y',$now));
        $this->assign('month',date('m',$now));
        $this->assign('vote', $vote);
        $this->assign('dayVotes',$dayVotes);
        $this->display();
    }
    
    // 异步获取每日得票数据
    public function getDayVoteAction()
    {
        $driver_id = I('driver_id', 0, 'intval');
        $date = I('date');
        $votes = $this->getDayVote($driver_id, $date);
        $this->ajaxSuccess('获取成功', $votes);
    }
    
    public function getIpRepeatAction() {
    	$driverId = I('id', 0, 'intval');
    	$term_id = I('term_id', 0, 'intval');
    	$condition = array(
    		'term_id' => $term_id,
    	);
    	$driverId and $condition['driver_id'] = $driverId;
    	$list = M("DriverVote")->where($condition)->group("ip")->field("COUNT( ip ) count, ip")->having("count>1")->order("count desc")->select();
    	$sum = 0;
    	foreach ( $list as $v ) {
    		$sum += ($v['count'] - 1);
    	}
    	$this->assign("total", $sum);
    	$this->assign("iplist", $list);
    	$this->display();
    }
    
    // 获取某一日得票数据
    private function getDayVote($driver_id, $date)
    {
        $timeStart = strtotime($date);
        $timeEnd = $timeStart + 24 * 60 * 60 - 1;
        $votes = $this->getVotesBetween($driver_id, $timeStart, $timeEnd);
        $votes['date'] = $date;
        return $votes;
    }
    
    // 获取一个时间段内的得票情况
    private function getVotesBetween($driver_id, $timeStart, $timeEnd)
    {
        $condition = array(
            'cid' => $this->aid,
            'term_id' => $this->termId,
            'driver_id' => $driver_id,
            '_string' => "create_time>= $timeStart AND create_time <= $timeEnd"
        );
        $lists = M('DriverVote')->where($condition)
            ->field('create_time t')
            ->order('t ASC')
            ->select();
        return array(
            'lists' => $lists,
            'count' => count($lists),
            'timeStart' => $timeStart,
            'timeEnd' => $timeEnd
        );
    }
    
    // 查看某24小时内的得票分布情况
    private function getVoteLists($driver_id, $timeEnd)
    {
        $timeStart = $timeEnd - 24 * 60 * 60 + 1;
        
        $condition = array(
            'cid' => $this->aid,
            'term_id' => $this->termId,
            'driver_id' => $driver_id,
            '_string' => "create_time> $timeStart AND create_time < $timeEnd"
        );
        $lists = M('DriverVote')->where($condition)
            ->field('create_time t')
            ->order('t ASC')
            ->select();
        return array(
            'lists' => $lists,
            'count' => count($lists),
            'timeStart' => $timeStart,
            'timeEnd' => $timeEnd
        );
    }
    
    // 查看每个司机的得票明细
    public function voteListAction()
    {
        $startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
        $endDate = I('endDate', 0, 'intval') or $endDate = time();
        $id = I('id', 0, 'intval');
        $condition = array(
            'cid' => $this->aid,
            'term_id' => $this->termId,
            'driver_id' => $id,
            'create_time' => array(
                array(
                    'egt',
                    $startDate
                ),
                array(
                    'elt',
                    $endDate
                ),
                'and'
            )
        );
        $m = M("DriverVote")->where($condition);
        $n = clone $m;
        $count = $n->count();
        $lists = $m->page($this->getPage())
            ->limit($this->getPageSize())
            ->order('id DESC')
            ->select();
        $params = array(
            'id' => $id,
            'term_id' => $this->termId,
            'startDate' => $startDate,
            'endDate' => $endDate
        );
        $this->showPage($count, $this->getPageSize(), $params);
        $this->assign("params", $params);
        $this->assign("lists", $lists);
        $this->display();
    }
    
    // 设置审核状态
    public function setVerifyStatusAction()
    {
        $id = I('id', 0, 'intval');
        $verify = I('status', 0, 'intval');
        if (false !== M("Driver")->where(array(
            'id' => $id,
            'cid' => $this->aid
        ))->setField('status', $verify)) {
            $verify or $this->clearOneRank();
            $this->ajaxSuccess("设置成功 ");
        }
        $this->ajaxSuccess("设置失败");
    }
    
    /*
     * // 清除排名 public function clearRankAction() { M('Driver')->where("cid=%d", $this->aid)->setField('vote', 0); false !== $this->rank->clear() and false !== M('DriverVote')->where("driver_id in ".M('Driver')->where("cid=%d", $this->aid)->field('id')->select(false))->delete() and $this->ajaxSuccess("清除成功!"); $this->ajaxSuccess("清除失败!"); }
     */
    
    // 移除
    public function removeAction()
    {
        $this->addEventListener("afterRemove", function ($e, $scope)
        {
            call_user_method("clearOneRank", $scope);
        });
        $this->ajaxRemove();
    }
    
    // 回收站
    public function recycleAction()
    {
        $this->setLinkNav(false);
        $this->getLists(1);
    }

    /**
     * 获得期次配置
     *
     * @return mixed
     */
    private function getTermConfig()
    {
        $driverTerm = M('DriverTerm')->where('cid=%d', $this->aid)->find($this->termId);
        return unserialize($driverTerm['config']);
    }
    
    // 清除单个排行
    public function clearOneRank()
    {
        $key = I("id", 0, 'intval');
        return false !== $this->rank->delete($key) and false !== M('Driver')->where("cid=%d and id=%d", $this->aid, $key)->setField('vote', 0) and false !== M('DriverVote')->where("driver_id=%d", $key)->delete();
    }
    
    // 投票数据
    private function voteSearch($params)
    {
        $condition = array(
            'cid' => $this->aid,
            'term_id' => $this->termId,
            'driver_id' => I('id', 0, 'intval'),
            'create_time' => array(
                array(
                    'egt',
                    $params['startDate']
                ),
                array(
                    'elt',
                    $params['endDate']
                ),
                'and'
            )
        );
        $lists = M("DriverVote")->where($condition)
            ->order('id DESC')
            ->select();
        return $lists;
    }

    /**
     * 导出Excel
     */
    public function exportXLSDriverVoteAction()
    {
        $startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
        $endDate = I('endDate', 0, 'intval') or $endDate = time();
        $params = array(
            'startDate' => $startDate,
            'endDate' => $endDate
        );
        $productOrderGoodsLists = $this->voteSearch($params);
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()
            ->setCreator("微美风铃")
            ->setLastModifiedBy("微美风铃")
            ->setTitle("投票记录")
            ->setSubject("投票记录")
            ->setDescription("投票记录")
            ->setKeywords("投票 记录")
            ->setCategory("投票记录");
        
        /* 设置标题 */
        $titles = array(
            '投票人微信号',
            'IP地址',
            '投票时间'
        );
        $fields = array(
            'open_id' => array(
                'type' => 'string'
            ),
            'ip' => array(
                'type' => 'string'
            ),
            'create_time' => array(
                'type' => 'datetime',
                'format' => 'Y/m/d H:i:s'
            )
        );
        $sheet0 = $objPHPExcel->setActiveSheetIndex(0);
        $rowNumber = 1;
        foreach ($titles as $k => $v) {
            $sheet0->setCellValue(chr(ord('A') + $k) . $rowNumber, $v);
        }
        $rowNumber ++;
        foreach ($productOrderGoodsLists as $v) {
            $fieldIndex = 0;
            foreach ($fields as $k0 => $v0) {
                $cellName = chr(ord('A') + $fieldIndex ++) . $rowNumber;
                $sheet0->setCellValueExplicit($cellName, $this->getShowData($v[$k0], $v0), $this->getCellFormat($v[$k0]));
                // $sheet0->setCellValue(chr(ord('A')+$fieldIndex++).$rowNumber, $this->getShowData($v[$k0], $v0));
            }
            $rowNumber ++;
        }
        $objPHPExcel->getActiveSheet()->setTitle(date('Y年m月d', $params['startDate']) . '至' . date('Y年m月d', $params['endDate']) . "投票记录");
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . date("Ymdhis") . '.xls"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1'); // IE9时
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

    /**
     * 获得单元格格式
     *
     * @param unknown $fieldCfg            
     * @return string
     */
    private function getCellFormat($fieldCfg)
    {
        if ($fieldCfg['type'] == 'string') {
            return \PHPExcel_Cell_DataType::TYPE_STRING;
        }
        return \PHPExcel_Cell_DataType::TYPE_STRING;
    }

    /**
     * 获得数据展示格式
     *
     * @param unknown $value            
     * @param unknown $fieldCfg            
     * @return string|unknown
     */
    private function getShowData($value, $fieldCfg)
    {
        if ($fieldCfg['type'] == 'datetime') {
            return date($fieldCfg['format'], $value);
        }
        return $value;
    }
    
    public function getIpAddressAction(){
        $ip = I('ip');
        $api = "http://ip.taobao.com/service/getIpInfo.php?ip=";
        $code = file_get_contents($api.$ip);
        echo $code;
    }
}